<template>
  <div class="container">
    <Breadcrumb :items="['系统管理', '用户管理']" />
    <a-card class="general-card" :title="$t('用户管理')">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="searchForm"
            label-align="left"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-layout="inline"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="username" :label="$t('用户账号')">
                  <a-input
                    v-model="searchForm.username"
                    :placeholder="$t('请输入用户账号')"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="mobile" :label="$t('手机号码')">
                  <a-input
                    v-model="searchForm.mobile"
                    :placeholder="$t('请输入手机号码')"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="status" :label="$t('状态')">
                  <a-select
                    v-model="searchForm.status"
                    :placeholder="$t('请选择状态')"
                    allow-clear
                  >
                    <a-option :value="UserStatusEnum.ENABLED">正常</a-option>
                    <a-option :value="UserStatusEnum.DISABLED">停用</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="16">
                <a-space>
                  <a-button type="primary" @click="search">
                    <template #icon>
                      <icon-search />
                    </template>
                    {{ $t('搜索') }}
                  </a-button>
                  <a-button @click="reset">
                    <template #icon>
                      <icon-refresh />
                    </template>
                    {{ $t('重置') }}
                  </a-button>
                  <a-button
                    type="primary"
                    status="success"
                    @click="openCreateForm"
                  >
                    <template #icon>
                      <icon-plus />
                    </template>
                    {{ $t('新增用户') }}
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-table
        row-key="id"
        :loading="loading"
        :data="renderData"
        :pagination="pagination"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
        :bordered="false"
      >
        <template #columns>
          <a-table-column title="用户账号" data-index="username" />
          <a-table-column title="用户昵称" data-index="nickName" />
          <a-table-column title="真实姓名" data-index="realName" />
          <a-table-column title="手机号码" data-index="mobile" />
          <a-table-column title="性别" data-index="gender">
            <template #cell="{ record }">
              {{ record.genderName || getGenderName(record.gender) }}
            </template>
          </a-table-column>
          <a-table-column title="状态" data-index="status">
            <template #cell="{ record }">
              <a-tag
                :color="
                  record.status === UserStatusEnum.ENABLED ? 'green' : 'red'
                "
              >
                {{ record.statusName || getStatusName(record.status) }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="创建时间" data-index="createTime">
            <template #cell="{ record }">
              {{ formatDateTime(record.createTime) }}
            </template>
          </a-table-column>
          <a-table-column title="操作" fixed="right" :width="240">
            <template #cell="{ record }">
              <a-space>
                <a-button
                  type="text"
                  size="small"
                  @click="openEditForm(record)"
                >
                  编辑
                </a-button>
                <a-button
                  type="text"
                  size="small"
                  status="danger"
                  @click="confirmDelete(record)"
                >
                  删除
                </a-button>
                <a-button
                  type="text"
                  size="small"
                  :status="
                    record.status === UserStatusEnum.ENABLED
                      ? 'danger'
                      : 'success'
                  "
                  @click="toggleStatus(record)"
                >
                  {{
                    record.status === UserStatusEnum.ENABLED ? '禁用' : '启用'
                  }}
                </a-button>
                <a-button
                  type="text"
                  size="small"
                  status="warning"
                  @click="openResetPasswordForm(record)"
                >
                  重置密码
                </a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 用户表单对话框 -->
    <a-modal
      v-model:visible="formVisible"
      :title="formTitle"
      :width="700"
      @before-ok="handleSubmitForm"
      unmount-on-close
    >
      <user-form ref="formRef" :form-data="formData" :is-edit="isEdit" />
      <template #footer>
        <a-space>
          <a-button @click="formVisible = false">取消</a-button>
          <a-button type="primary" @click="submitForm"> 确定 </a-button>
        </a-space>
      </template>
    </a-modal>

    <!-- 重置密码对话框 -->
    <a-modal
      v-model:visible="resetPwdVisible"
      title="重置密码"
      @before-ok="handleResetPassword"
      unmount-on-close
    >
      <a-form
        ref="resetPwdFormRef"
        :model="resetPwdForm"
        :label-col-props="{ span: 6 }"
        :wrapper-col-props="{ span: 18 }"
      >
        <a-form-item
          field="password"
          label="新密码"
          :rules="[{ required: true, message: '请输入新密码' }]"
        >
          <a-input-password
            v-model="resetPwdForm.password"
            placeholder="请输入新密码"
            allow-clear
          />
        </a-form-item>
        <a-form-item
          field="confirmPassword"
          label="确认密码"
          :rules="confirmPasswordRules"
        >
          <a-input-password
            v-model="resetPwdForm.confirmPassword"
            placeholder="请再次输入新密码"
            allow-clear
          />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-space>
          <a-button @click="resetPwdVisible = false">取消</a-button>
          <a-button type="primary" @click="confirmResetPassword">
            确定
          </a-button>
        </a-space>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, computed, onMounted } from 'vue';
  import { Message, Modal } from '@arco-design/web-vue';
  import useLoading from '@/hooks/loading';
  import dayjs from 'dayjs';
  import {
    IconSearch,
    IconRefresh,
    IconPlus,
  } from '@arco-design/web-vue/es/icon';
  import {
    getUserList,
    getUserDetail,
    deleteUser,
    enableUser,
    disableUser,
    resetUserPassword,
    User,
    UserGenderEnum,
    UserStatusEnum,
    UserQueryParams,
  } from '@/api/system/user';
  import UserForm from './components/user-form.vue';

  const { loading, setLoading } = useLoading();
  const renderData = ref<User[]>([]);
  const formRef = ref();
  const formVisible = ref(false);
  const isEdit = ref(false);
  const formData = ref<Partial<User>>({});

  // 搜索表单
  const searchForm = reactive<UserQueryParams>({
    username: '',
    mobile: '',
    status: undefined,
    current: 1,
    size: 10,
  });

  // 分页配置
  const pagination = reactive({
    total: 0,
    current: 1,
    pageSize: 10,
    showTotal: true,
    showPageSize: true,
    pageSizeOptions: [10, 20, 50],
  });

  // 重置密码表单
  const resetPwdFormRef = ref();
  const resetPwdVisible = ref(false);
  const resetPwdForm = reactive({
    userId: 0,
    password: '',
    confirmPassword: '',
  });

  // 确认密码验证规则
  const confirmPasswordRules = [
    { required: true, message: '请再次输入新密码' },
    {
      validator: (value: string, cb: (error?: string) => void) => {
        if (value !== resetPwdForm.password) {
          return cb('两次输入的密码不一致');
        }
        return cb();
      },
    },
  ];

  // 表单标题
  const formTitle = computed(() => {
    return isEdit.value ? '编辑用户' : '新增用户';
  });

  // 格式化日期时间
  function formatDateTime(date: string | undefined) {
    if (!date) return '-';
    return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
  }

  // 获取性别名称
  function getGenderName(gender: number | undefined) {
    const genderMap = {
      [UserGenderEnum.UNKNOWN]: '未知',
      [UserGenderEnum.MALE]: '男',
      [UserGenderEnum.FEMALE]: '女',
    };
    return gender !== undefined
      ? genderMap[gender as keyof typeof genderMap]
      : '-';
  }

  // 获取状态名称
  function getStatusName(status: number | undefined) {
    const statusMap = {
      [UserStatusEnum.ENABLED]: '正常',
      [UserStatusEnum.DISABLED]: '停用',
    };
    return status !== undefined
      ? statusMap[status as keyof typeof statusMap]
      : '-';
  }

  // 查询数据
  async function fetchData() {
    setLoading(true);
    try {
      const params = {
        ...searchForm,
        pageNum: pagination.current,
        pageSize: pagination.pageSize,
      };
      const res = await getUserList(params);
      renderData.value = res.data.records;
      pagination.total = res.data.total;
    } catch (err) {
      console.error('获取用户列表出错:', err);
      Message.error('获取用户列表失败');
    } finally {
      setLoading(false);
    }
  }

  // 开启新增表单
  function openCreateForm() {
    isEdit.value = false;
    formData.value = {
      status: UserStatusEnum.ENABLED,
      gender: UserGenderEnum.UNKNOWN,
    };
    formVisible.value = true;
  }

  // 开启编辑表单
  async function openEditForm(record: User) {
    try {
      const res = await getUserDetail(record.id!);
      formData.value = res.data;
      isEdit.value = true;
      formVisible.value = true;
    } catch (err) {
      console.error('获取用户详情出错:', err);
      Message.error('获取用户详情失败');
    }
  }

  // 确认删除
  function confirmDelete(record: User) {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除用户 "${record.username}" 吗？此操作不可恢复。`,
      onOk: async () => {
        try {
          await deleteUser(record.id!);
          Message.success('删除用户成功');
          fetchData();
        } catch (err) {
          console.error('删除用户出错:', err);
          Message.error('删除用户失败');
        }
      },
    });
  }

  // 切换用户状态
  async function toggleStatus(record: User) {
    const newStatus =
      record.status === UserStatusEnum.ENABLED
        ? UserStatusEnum.DISABLED
        : UserStatusEnum.ENABLED;
    const actionName = newStatus === UserStatusEnum.ENABLED ? '启用' : '禁用';

    Modal.confirm({
      title: `确认${actionName}`,
      content: `您确定要${actionName}用户 "${record.username}" 吗？`,
      onOk: async () => {
        try {
          if (newStatus === UserStatusEnum.ENABLED) {
            await enableUser(record.id!);
          } else {
            await disableUser(record.id!);
          }
          Message.success(`${actionName}成功`);
          fetchData();
        } catch (err) {
          console.error(`${actionName}用户出错:`, err);
          Message.error(`${actionName}失败`);
        }
      },
    });
  }

  // 打开重置密码表单
  function openResetPasswordForm(record: User) {
    resetPwdForm.userId = record.id!;
    resetPwdForm.password = '';
    resetPwdForm.confirmPassword = '';
    resetPwdVisible.value = true;
  }

  // 提交重置密码
  async function handleResetPassword(done: any) {
    if (!resetPwdFormRef.value) {
      done(false);
      return;
    }

    resetPwdFormRef.value.validate(async (errors: any) => {
      if (errors) {
        done(false);
        return;
      }

      try {
        await resetUserPassword(resetPwdForm.userId, resetPwdForm.password);
        Message.success('重置密码成功');
        done();
      } catch (error) {
        console.error('重置密码失败:', error);
        Message.error('重置密码失败');
        done(false);
      }
    });
  }

  // 确认重置密码
  function confirmResetPassword() {
    if (!resetPwdFormRef.value) {
      return;
    }

    resetPwdFormRef.value.validate(async (errors: any) => {
      if (errors) {
        return;
      }

      try {
        await resetUserPassword(resetPwdForm.userId, resetPwdForm.password);
        Message.success('重置密码成功');
        resetPwdVisible.value = false;
      } catch (error) {
        console.error('重置密码失败:', error);
        Message.error('重置密码失败');
      }
    });
  }

  // 提交表单
  async function handleSubmitForm(done: any) {
    try {
      if (!formRef.value) {
        console.error('表单引用不存在');
        Message.error('表单引用不存在');
        done(false);
        return;
      }

      const valid = await formRef.value.validate();

      if (valid) {
        const result = await formRef.value.submit();

        if (result) {
          fetchData();
          done();
        } else {
          done(false);
        }
      } else {
        Message.warning('表单验证未通过，请检查表单内容');
        done(false);
      }
    } catch (err) {
      console.error('提交表单出错:', err);
      Message.error('提交失败');
      done(false);
    }
  }

  // 手动提交表单
  async function submitForm() {
    try {
      if (!formRef.value) {
        Message.error('表单引用不存在');
        return;
      }

      const valid = await formRef.value.validate();

      if (valid) {
        const result = await formRef.value.submit();

        if (result) {
          formVisible.value = false;
          fetchData();
        }
      } else {
        Message.warning('表单验证未通过，请检查表单内容');
      }
    } catch (err) {
      console.error('手动提交出错:', err);
      Message.error('提交失败，请检查表单');
    }
  }

  // 搜索
  function search() {
    pagination.current = 1;
    fetchData();
  }

  // 重置
  function reset() {
    searchForm.username = '';
    searchForm.mobile = '';
    searchForm.status = undefined;
    pagination.current = 1;
    fetchData();
  }

  // 分页变化
  function onPageChange(current: number) {
    pagination.current = current;
    fetchData();
  }

  // 每页条数变化
  function onPageSizeChange(pageSize: number) {
    pagination.pageSize = pageSize;
    pagination.current = 1;
    fetchData();
  }

  // 初始化
  onMounted(() => {
    fetchData();
  });
</script>

<style scoped lang="less">
  .container {
    padding: 0 20px 20px 20px;
  }

  .general-card {
    margin-top: 16px;

    :deep(.arco-card-header) {
      border-bottom: 1px solid var(--color-border-2);
      padding: 16px 20px;
    }
  }

  :deep(.arco-table-th) {
    &:last-child {
      .arco-table-th-item-title {
        margin-left: 16px;
      }
    }
  }
</style>
